#!/user/bin/env python3
# -*- coding: utf-8 -*-

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt



def custom_hist(gray):
    '''
    自定义求图像脂肪图的函数，通过遍历每一个像素值，进行数学统计后求得图像直方图
    :param gray:
    :return:
    '''
    h, w = gray.shape
    hist = np.zeros([256], dtype=np.int32)
    for row in range(h):
        for col in range(w):
            pv = gray[row, col]
            hist[pv] += 1
    y_pos = np.arange(0, 256, 1, dtype=np.int32)
    plt.bar(y_pos, hist, align='center', color='r', alpha=0.5)
    plt.xticks(y_pos, y_pos)
    plt.ylabel("Frequency")
    plt.xlabel("Histogram")
    # plt.plot(hist, color='r')
    # plt.xlim([0, 256])
    plt.show()

def image_hist(image):
    cv.imshow("input", image)
    color = ('blue', 'green', 'red')
    for i, color in enumerate(color):
        hist = cv.calcHist([image], [i], None, [256], [0, 256])
        plt.plot(hist, color=color)
        plt.xlim([0, 256])
    plt.show()

file = r'D:\data\aloeL.jpg'
src = cv.imread(file)
cv.imshow("input image", src)
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
cv.imshow("input", gray)
custom_hist(gray)
image_hist(src)

#使用OTSU即大津算法对图像进行二值化：首先将图像转换为灰度图像，然后用OTSU求得而知图


ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
print("ret", ret)
cv.imshow("hist image", binary)

cv.waitKey()
cv.destroyAllWindows()